<?php
require_once('../phplib/include.inc.php');

class DoAddUser{
	private $db;
	public function DoAdd(){
		Util::ValidateRight(1);
		$this->db = getDb();
		$this->db->connect();
		$this->ParseRequest();
		$uid = $this->AddUser();
		$this->AddRight($uid);
		Util::AddLog("添加用户：".$_REQUEST['uname'].",添加后用户的id为： $uid ");
		PageBase::Go('../home/useradmin.php');
	}
	public function ParseRequest(){
		$R = $_REQUEST;
		if(strlen($R['uname']) == 0) PageBase::Error('请先填写用户名.');
		if(strlen($R['pwd']) == 0 || strlen($R['pwd']) > 20) PageBase::Error('用户密码长度为1~20位.');
		if(strlen($R['job']) == 0) PageBase::Error('请正确填写职位');
		$db = getDb();
		$db->connect();
		$re = $db->fetch("SELECT * FROM user_t WHERE uname={0}",$R['uname']);
		if(count($re) > 0) PageBase::Error('该用户已经存在，请另选一个.');
		
	}
	public function AddUser(){
		$R = $_REQUEST;		
		/* @var $db DbMySQL */
		$this->db->startTrans();
		$re = $this->db->execute("INSERT INTO `user_t`(uname,pwd,job,regtime,lastlogin)VALUES({0},{1},{2},{3},{4})",array($R['uname'],md5($R['pwd']),$R['job'],date("Y-m-d H:i:s"),date("Y-m-d H:i:s")));
		if(intval($re) != 1){
			$this->db->rollbackTrans();
			PageBase::Error('添加用户过程中出错了，未知错误，请与技术人员联系');
		}
		return $this->db->insertId();
	}
	public function AddRight($uid){
		$R = $_REQUEST;
		$sql = "INSERT INTO right_t(rid,uid) VALUES ";
		$products = $this->db->fetch("SELECT * FROM product_t");
		if(isset($R['useradmin'])) $sql .= "(1,$uid),";
		if(isset($R['addproduct'])) $sql .= "(2,$uid),";
		if(isset($R['addtype'])) $sql .= "(3,$uid),";
		if(isset($R['modifytype'])) $sql .= "(4,$uid),";
		if(isset($R['deletetype'])) $sql .= "(5,$uid),";
		for($i=0;$i<count($products);$i++){
			$pid = $products[$i]['pid'];
			if(isset($R['viewproduct'.$pid])) $sql .= "(".(intval($pid)*10 + 0).",$uid),";
			if(isset($R['modifyproduct'.$pid])) $sql .= "(".(intval($pid)*10 + 1).",$uid),";
			if(isset($R['deleteproduct'.$pid])) $sql .= "(".(intval($pid)*10 + 2).",$uid),";
		}
		if(substr($sql,strlen($sql) - 1) != ","){
			$this->db->rollbackTrans();
			PageBase::Error('请给该用户分配权限.');
		}
		$sql = substr($sql,0,strlen($sql)-1);
		$sql .= ';';
		$re = $this->db->execute($sql);
		if(intval($re) < 1){
			$this->db->rollbackTrans();
			PageBase::Error('添加用户权限过程中出错了，未知错误，请与技术人员联系');
		}
		$this->db->commitTrans();
		return $this->db->insertId();
	}
}
$doadduser = new DoAddUser();
$doadduser->DoAdd();
?>